<?php
  defined('ACC')||exit('ACC Denied'); 
  class companymodel extends model{
    public function insertelement($table, $data){
       $this->table($table);
       $this->add($data);
       return $this->db->insert_id();
    } 
    
    /*
    public function insertaccount($accountid,$conpanyid,$balance,$debitcredit){
       $this->table('account_balance');
       return $this->add(array('account_id'=>$accountid, 'company_id'=>$companyid, 'account_balance'=>$balance, 'debit_credit'=>$debitcredit));
    }
    */

    public function creatcompany($userid, $companyname){
       /*
       
       $sql = 'select count(*) from company where user_id = ' . $userid;
       $alreadycreated = $this->db->getOne($sql);       
       if ($alreadycreated>0){
           return false; //已经生成过公司了；
       }
       */
       
       $datetime = date('Y-m-d H:i:s', time());
       $this->table('company'); 
       $this->add(array('company_name'=>$companyname, 'user_id'=>$userid, 'create_time'=>$datetime,'company_category'=>'初具规模型', 'company_y'=>0, 'company_q'=>1));
       $sql = 'select company_id from company where user_id = ' . $userid;
       $companyid = $this->db->getOne($sql);
       //return $companyid;

       //$fh = fopen(ROOT . 'data/initialstatus.txt', 'r');
       $initialstatus = file_get_contents(ROOT . 'data/initialstatus.txt',true);
       //return $initialstatus;
       $elementsstr = $this->findbetween($initialstatus, '{', '}');
       $right = $this->findright($initialstatus, '}'); 
       $accountsstr =  $this->findbetween($right, '{', '}');
       //return $elementsstr; 
                                                                                                                                                                                                                                                                                   
       $elements = array();
       $rest = $elementsstr;
       while(($this->findbetween($rest, '[', ')'))!=false){
           $elements[] = $this->findbetween($rest, '[', ')');
           $rest = $this->findright($rest, ')');
       }
       
       $listbuilding = array();
       $listequipment = array();
       
       // return $elements;
       
       //$input = array();
       foreach($elements as $k => $v){
           
           $tb = $this->findleft($v,']');
           //$this->table($tb); 
           $input = array();                      
           $elementrest = $this->findright($v, '(');            
           while(($this->findleft($elementrest, ';'))!=false){
               $input[] = $this->findleft($elementrest, ';');
               $elementrest = $this->findright($elementrest, ';');
           }
           //return $input;
           //$input[] = $table;
           //$input[] = $rest;
               
               
               switch ($tb){
               
               // building 放置厂房信息，其中格式为：厂房ID:厂房数量|厂房原值|厂房残值|还需建设的时间 
               case 'building':
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $num = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['original_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|'); 
                    $row['building_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['construct_period'] = $inputrest;
                    $row['company_id'] = $companyid;
                    //return $rest;
                    for($i=1; $i<= $num; $i++){
                        $building_tagid = $this->insertelement($tb, $row);
                        $buildingelementid = $this->db->getOne('select element_id from building where building_tagid = ' . $building_tagid);
                        $buildingsize = $this->db->getOne('select building_size from building_list where element_id = ' . $buildingelementid);
                        if($row['construct_period'] == 0){
                            $listbuilding[$building_tagid] = $buildingsize;
                        }
                    }
                    }
                    break;
                    //return $row;
               
               //cash_equivalent 放置现金或者现金等价物，其中格式为：现金ID:金额|存放形式
               case 'cash_equivalent':
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $row['original_value'] = $row['current_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['format'] = $inputrest;
                    $row['company_id'] = $companyid;
                    //return $rest;
                    $this->insertelement($tb, $row);
                    }
                    break; 
                    //return $row;
               
               
               
               // equipment 放置生产线信息，其中格式为：生产线ID:生产线数量|生产线原值|生产线残值|还需安装的时间 
               case 'equipment':
                    
                    $position = 1;
                    
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $num = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['original_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|'); 
                    $row['element_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['installation_period'] = $inputrest;
                    $row['company_id'] = $companyid;
                    
                    //return $rest;
                    for($i=1; $i<= $num; $i++){
                        if(empty($listbuilding)){
                            return false;//厂房不够放置生产线了；
                        }   
                        reset($listbuilding);
                        $row['building_tagid'] = key($listbuilding);
                        $row['position_in_building'] = $position;
                        $position = $position+1;
                        
                        if($position>current($listbuilding)){
                        array_shift($listbuilding);
                        $position = 1;
                        } 
                        $equipmenttagid = $this->insertelement($tb, $row);
                        
                        if($row['installation_period'] == 0){
                        $listequipment[] = $equipmenttagid;
                        }
                    }
                    }
                    break;                 
               
               // loan 放置贷款信息，其中格式为：贷款ID:贷款金额|还款期限|年利率 
               
               case 'loan':
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $row['original_value'] = $row['current_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|'); 
                    $row['duration'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['interest_rate'] = $inputrest;
                    $row['company_id'] = $companyid;
                    //return $rest;
                    $this->insertelement($tb, $row);
                    }
                    break; 
               
               //raw_material 放置原材料信息，其中格式为：原材料ID:原材料数量|原材料价值|等待入库的时间
               case 'raw_material':
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $num = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['element_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|'); 
                    $row['raw_material_trans'] = $inputrest;
                    $row['company_id'] = $companyid;
                    //return $rest;
                    for($i=1; $i<= $num; $i++){
                        $this->insertelement($tb, $row);
                    }
                    }
                    break;
               
               // product 放置在产品信息，其中格式为：产品ID:在产品数量|在产品成本|还需生产的时间 
               case 'product':           
                    foreach($input as $key=>$value){
                    $row = array();
                    $num=1;
                    $inputrest = $value; 
                    $row['element_id'] = $this->findbetween($inputrest, '!', ':');
                    $inputrest = $this->findright($inputrest, ':');
                    $num = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|');
                    $row['product_value'] = $this->findleft($inputrest, '|');
                    $inputrest = $this->findright($inputrest, '|'); 
                    $row['produce_period'] = $inputrest;
                    $row['company_id'] = $companyid;
                    //return $rest;
                    if($row['produce_period']>0){                    
                        for($i=1; $i<= $num; $i++){
                            if(empty($listequipment)){
                                return false;//生产线不够放置在产品了；
                            }
                            reset($listequipment); 
                            $row['equipment_tagid'] = current($listequipment);
                            array_shift($listequipment);
                            $this->insertelement($tb, $row);
                        }
                    
                    }else{
                        for($i=1; $i<= $num; $i++){
                            $row['equipment_tagid'] = 0;
                            $this->insertelement($tb, $row);
                        } 
                    }
                    }
                    
                    break; 
           }  
       }
       
       
       // elements 放置的企业的所有报表元素 ,格式为：账户id:账户余额|借贷 
       $accounts = array();
       $rest = $accountsstr;
       while(($this->findbetween($rest, '!', ';'))!=false){
           $accounts[] = $this->findbetween($rest, '!', ';');
           $rest = $this->findright($rest, ';');
       }
       
       //return $accounts;
       
       foreach($accounts as $key=>$value){
           $row = array();
           $accountrest = $value;
           $row['account_id'] = $this->findleft($accountrest, ':');
           $accountrest = $this->findright($accountrest, ':');
           $row['account_balance'] = $this->findleft($accountrest, '|');
           $accountrest = $this->findright($accountrest, '|');
           $row['debit_credit'] = $accountrest;
           $row['company_id'] = $companyid;        
           $this->insertelement('account_balance', $row);
           
       }
       $sql = 'select company_id, company_name, create_time, company_category from company where user_id = ' . $userid;
         
       return $this->db->getRow($sql); 
    }
    
    
    
    
    public function findbetween($string, $startstr, $endstr){
        if((stripos($string, $startstr)==false)||(stripos($string, $endstr)==false)){
        return false;
        }else{
            $start =  stripos($string, $startstr);
            $end = stripos($string, $endstr);
            $len = strlen($string);
            return substr($string, $start + 1,$end - $start-1);  
        }
    }
    
    public function  findright($string, $endstr) {
        if(stripos($string, $endstr)==false){
        return false;
        }else{
            $end = stripos($string, $endstr);
            $len = strlen($string);
            return  substr($string, $end+1, strlen($string)-($end+1)); 
        }
    }
    
    public function findleft($string, $startstr){
       if(stripos($string, $startstr)==false){
        return false;
        }else{
            $start = stripos($string, $startstr);
            $len = strlen($string);
            return  substr($string, 0, $start); 
        }
    
    }
    
    public function getcompanyinfo($userid){
        $sql = 'select * from company where user_id = ' .  $userid;
        return $this->db->getRow($sql);
    }
       
    public function getallelements($company_id, $element_name){
        $sql = "select * from " . $element_name . " where company_id = " . $company_id . " and deleteflg not in ('deleted', 'archived' )";
        return $this->db->getAll($sql); 
    }
    
    public function getelementinfo($tagid, $element_name){
        $sql = 'select element_id from ' . $element_name . ' where ' . $element_name . '_tagid = ' . $tagid;
        $element_id = $this->db->getOne($sql);             
        $sql = 'select * from ' . $element_name . '_list where element_id = ' .  $element_id;
        $row =  $this->db->getRow($sql);
        $sql = 'select element_name from company_element_list where element_id = ' .  $element_id; 
        $row['element_name'] = $this->db->getOne($sql);
        return $row;
    }
    
    public function getequipment($building_tagid, $position){
        $sql = "select * from equipment where building_tagid = " . $building_tagid . " and position_in_building = " . $position . " and deleteflg not in ('deleted', 'archived' )";
        return $this->db->getRow($sql); 
    }
    
    public function getunfinishedgood($equipment_tagid){
        $sql = "select * from product where equipment_tagid = " . $equipment_tagid . " and produce_period > 0 and deleteflg not in ('deleted', 'archived' )";
        return $this->db->getRow($sql); 
    }
    
    public function getrawmaterialontheway($company_id){
        $sql = "select * from raw_material where company_id = " . $company_id . " and raw_material_trans > 0 and deleteflg not in ('deleted', 'archived' ) order by element_id asc";
        $rawmaterialontheway = $this->db->getAll($sql);
        $tmp = array();
        $row = array();
        $key = '';
        $num = 0;
        
        if(empty($rawmaterialontheway)){
            return $row;
        } 
        
        reset($rawmaterialontheway);
        $tmp = current($rawmaterialontheway);
        $elementid = $tmp['element_id'];
        $num = 1;
        array_shift($rawmaterialontheway);
        
        while(!empty($rawmaterialontheway)){
            reset($rawmaterialontheway);
            $tmp = current($rawmaterialontheway);
            if($tmp['element_id'] != $elementid){
                $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
                $key = $this->db->getOne($sql); 
                $row[$key] = $num; 
                $elementid = $tmp['element_id'];
                $num = 1;
                array_shift($rawmaterialontheway);
            }else{
                $num = $num + 1;
                array_shift($rawmaterialontheway);
            }
        }
        $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
        $key = $this->db->getOne($sql); 
        $row[$key] = $num;
        return $row;
    }        
            

  
    
    public function getrawmaterialinstock($company_id){
        $sql = "select * from raw_material where company_id = " . $company_id . " and raw_material_trans = 0 and deleteflg not in ('deleted', 'archived' ) order by element_id asc";
        $rawmaterialinstock = $this->db->getAll($sql);
        
        $tmp = array();
        $row = array();
        $key = '';
        $num = 0;
        
        if(empty($rawmaterialinstock)){
            return $row;
        } 
        
        reset($rawmaterialinstock);
        $tmp = current($rawmaterialinstock);
        $elementid = $tmp['element_id'];
        $num = 1;
        array_shift($rawmaterialinstock);
        
        
        while(!empty($rawmaterialinstock)){
            reset($rawmaterialinstock);
            $tmp = current($rawmaterialinstock);
            if($tmp['element_id'] != $elementid){
                $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
                $key = $this->db->getOne($sql);  
                $row[$key] = $num; 
                $elementid = $tmp['element_id'];
                $num = 1;
                array_shift($rawmaterialinstock);
            }else{
                $num = $num + 1;
                array_shift($rawmaterialinstock);
            }
        }
        $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
        $key = $this->db->getOne($sql); 
        $row[$key] = $num;
        return $row;
    }
    
        
    public function getfinishedgood($company_id){
        $sql = "select * from product where company_id = " . $company_id . " and produce_period = 0 and deleteflg not in ('deleted', 'archived' ) order by element_id asc";
        $finishedgood = $this->db->getAll($sql);     
    
        $tmp = array();
        $row = array();
        $key = '';
        $num = 0;
        
        if(empty($finishedgood)){
            return $row;
        } 
        
        
        //此函数是返回每一个产品的名字以及数量，代码写得很烂，完全有更好的办法（遍历product_list，然后来用select count来实现），懒得改了。
        reset($finishedgood);
        $tmp = current($finishedgood);
        $elementid = $tmp['element_id'];
        $num = 1;
        array_shift($finishedgood);
        
        while(!empty($finishedgood)){
            reset($finishedgood);
            $tmp = current($finishedgood);
            if($tmp['element_id'] != $elementid){
                $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
                $key = $this->db->getOne($sql); 
                $row[$key] = $num; 
                $elementid = $tmp['element_id'];
                $num = 1;
                array_shift($finishedgood);
            }else{
                $num = $num + 1;
                array_shift($finishedgood);
            }
        }
        $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
        $key = $this->db->getOne($sql); 
        $row[$key] = $num;
        return $row;
    
    }    
    
    public function getcash_equivalent($company_id){
        $sql = "select * from cash_equivalent where company_id = " . $company_id . " and deleteflg not in ('deleted', 'archived' ) order by element_id asc, current_value desc";
        $cash_equivalent = $this->db->getAll($sql);
        
        $tmp = array();
        $row = array();
        $key = '';
        $amount = 0;
        
        if(empty($cash_equivalent)){
            return $row;
        } 
        
        reset($cash_equivalent);
        $tmp = current($cash_equivalent);
        $elementid = $tmp['element_id'];
        $amount = $tmp['current_value'];
        array_shift($cash_equivalent); 
        
        while(!empty($cash_equivalent)){
            reset($cash_equivalent);
            $tmp = current($cash_equivalent);
            if($tmp['element_id'] != $elementid){
                $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
                $key = $this->db->getOne($sql);
                $row[$key] = $amount; 
                $elementid = $tmp['element_id'];
                $amount = $tmp['current_value'];
                array_shift($cash_equivalent);
            }else{
                $amount = $amount + $tmp['current_value'];
                array_shift($cash_equivalent);
            }
        }
        $sql = 'select element_name from company_element_list where element_id = ' . $elementid;  
        $key = $this->db->getOne($sql);
        $row[$key] = $amount;
        return $row; 
    }
    
    public function getloan($company_id){
        $sql = "select * from loan where company_id = " . $company_id . " and deleteflg not in ('deleted', 'archived' ) order by duration asc, current_value desc";
        $loan = $this->db->getAll($sql);
        
        $tmp = array();
        $row = array();
        $key = '';
        
        if(empty($loan)){
            return $row;
        } 
        
        reset($loan);
        $tmp = current($loan);
        $loanrow=array();
        $duration = $tmp['duration'];
        $elementid = $tmp['element_id'];
        array_shift($loan);
        
        
        while(!empty($loan)){
             reset($loan);
             $loanrow = current($loan);
             if(($tmp['element_id'] == $loanrow['element_id'])&&($tmp['duration'] == $loanrow['duration'])){
                 $tmp['current_value'] = $tmp['current_value'] + $loanrow['current_value'];
                 array_shift($loan); 
             }else{
                 $row[] = $tmp;
                 $tmp = $loanrow;
                 array_shift($loan);
             }
        }
        $row[] = $tmp;
        return $row;   
    }
    
    public function getelementlist($name){
        $sql = 'select * from ' . $name . '_list';               
        $elementlist = $this->db->getAll($sql);
        $row = array();
        foreach($elementlist as $k => $v){
            $item = $v;
            $elementid = $v['element_id'];
            $sql = 'select element_name from company_element_list where element_id = ' .  $elementid;
            $elementname = $this->db->getOne($sql);
            $item['element_name'] = $elementname;
            $row[] = $item;        
        }
        return $row; 
    }
    
    
    public function getnumofemptypositions($company_id){
        $buildinginfo = $this->getallelements($company_id, 'building');
        $numofemptypositions = 0;
        foreach($buildinginfo as $k=>$v){
            $constructperiod = $v['construct_period'];
            if($constructperiod == 0){
                $buildingtagid = $v['building_tagid'];
                $elementinfo = $this->getelementinfo($buildingtagid, 'building');
                $buildingsize = $elementinfo['building_size'];
                
                for($i=1;$i<=$buildingsize; $i++){
                    $equipment =  $this->getequipment($buildingtagid, $i);
                    if(empty($equipment)){
                        $numofemptypositions++;
                    } 
                }
            } 
        }
        return  $numofemptypositions; 
    }
    
    public function getnumofemptyequipments($company_id){
    
    
    
    }
    
    public function actionpurchasebuilding($company_id, $element_id, $num){
        
        
        $cashinfo = $this->getcash_equivalent($company_id);
        //echo '<h3>现金及现金等价物：'; 
        $cash = 0;
        $deposit = 0;
        $sql = 'select * from building_list where element_id = ' . $element_id;
        $elementinfo = $this->db->getRow($sql);
        $sql = 'select element_name from company_element_list where element_id = ' . $element_id;
        $elementinfo['element_name'] = $this->db->getOne($sql);        
        $building_value = $original_value = $elementinfo['building_price'];
        
        //以下代码用来判断资金是否足够购买这么多材料        
        foreach($cashinfo as $k=>$v){ 
            if($k == '库存现金'){
                $cash = $v;   
            }
            
            if($k == '银行存款'){
                $deposit = $v;
            }
        }
        $ttlcashequivalent = $cash + $deposit;        
        $action_amount =  $num * $building_value;  
        //echo $action_amount . '|||' . $ttlcashequivalent;
                
         if ($ttlcashequivalent< $action_amount){
            return false;         
         }
         
         //以下代码用来生成actionlog          
         $action_id =  7;
         
         //print_r($elementinfo);
         
         $element_name = $elementinfo['element_name'];
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '投资建设厂房：' . $element_name . '，数量：' . $num . '个。';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'element_id'=>$element_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_price'=>$building_value, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();  
        
        
        //以下代码输入新购买的元素
         $construct_period =  $elementinfo['construction_period'];
         $buildingtagidlist= array();
         $building = array('element_id'=>$element_id, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'original_value'=>$original_value, 'building_value'=>$building_value, 'construct_period'=>$construct_period);
    
         for($i=1; $i<=$num; $i++){
              $tagid = $this->insertelement('building', $building);
              $buildingtagidlist[] = $tagid; 
         } 
              
         //以下代码从银行存款及现金内削减相应的金额
         $this->deductcash($company_id, $action_amount); 
         

         
         //以下代码用来输入记账凭证
         $bookinginfo =array();
         if($deposit >=$action_amount ){
            //记账凭证:使用银行存款购买
            $bookinginfo[1604] = $action_amount;
            $bookinginfo[1002] =  - $action_amount;
            $this-> insertdailybooking ($actionlogid, $bookinginfo);

         }else{
            $bookinginfo[1604] = $action_amount;
            $bookinginfo[1002] =  - $deposit;
            $bookinginfo[1001] =  - ($action_amount - $deposit);
            $this-> insertdailybooking ($actionlogid, $bookinginfo); 
         }
         $row = array($actionlogid=>$buildingtagidlist);
         return $row;
    }
            
    

    public function insertdailybooking($action_log_id, $bookinginfo){
        $row = array();
        foreach($bookinginfo as $k=>$v){
            if($v>0){
                $debit_credit = 'debit';//正数表示debit            
            }else{
                $debit_credit = 'credit';//负数表示credit    
            }
            $bookinglog = array('action_log_id'=>$action_log_id, 'account_id'=>$k, 'amount'=>abs($v), 'debit_credit'=>$debit_credit, 'practised' =>0, 'posted'=>0);    
            $this->db->autoExecute($bookinglog, 'account_daily_booking' ,'insert');
            $row[] = $this->db->insert_id(); 
        }    
        return $row; 
    }
    
    public function deductcash($company_id, $amount){//先减银行存款，再减现金
        $cashinfo = $this->getcash_equivalent($company_id);
        $cash = 0;
        $deposit = 0;
        
        foreach($cashinfo as $k=>$v){ 
            if($k == '库存现金'){
                $cash = $v;   
            }
            
            if($k == '银行存款'){
                $deposit = $v;
            }
        }
        $ttlcashequivalent = $cash + $deposit;
        
        if($ttlcashequivalent<$amount){
            return false;
        }
        
        if($deposit>=$amount){
            $this->deductelement($company_id, 'cash_equivalent', 6002, $amount);       
        }else{
            $this->deductelement($company_id, 'cash_equivalent', 6002, $deposit);
            $this->deductelement($company_id, 'cash_equivalent', 6001, $amount - $deposit);         
        }
        return true;
    }
    
    public function deductelement($company_id, $element_table_name, $element_id, $amount){
        $sql = "select * from " . $element_table_name.  " where company_id =" . $company_id . " and element_id = " . $element_id. " and deleteflg not in ('deleted', 'archived' ) " ;    
        $elementinfo = $this->db->getAll($sql);
        $ttlvalue = 0;
        foreach($elementinfo as $k=>$v){
            $ttlvalue = $ttlvalue + $v['current_value'];
       }
       
       if($ttlvalue<$amount){
       return false;
       } 
       $rest = $amount;
       $arr = array();
       foreach($elementinfo as $k=>$v){
            $element_tagid = $v[$element_table_name . '_tagid'];
            $element_value = $v['current_value'];
            if($rest<$element_value){
                $arr['current_value'] = $element_value - $rest;                
                $this->db->autoExecute($arr, $element_table_name,'update', ' where ' . $element_table_name . '_tagid = ' . $element_tagid);
                break;
            }else{
                $arr['deleteflg'] = 'deleted';
                $rest = $rest -  $element_value;
                $this->db->autoExecute($arr, $element_table_name,'update', ' where ' . $element_table_name . '_tagid = ' . $element_tagid);
            } 
       }
       return true; 
    }
      
   public function  getactionlog($company_id, $num){
       $sql = "select * from action_log where company_id = " .$company_id. " and deleteflg not in ('deleted', 'archived' ) order by action_log_id limit " . $num;
       $row = $this->db->getAll($sql);
       return $row;
   }
   
   public function  getactionlogbyyq($company_id, $fiscal_year, $fiscal_quarter){
       $sql = "select * from action_log where company_id = " .$company_id. " and action_log_y = " . $fiscal_year.  " and action_log_q = " . $fiscal_quarter . " and deleteflg not in ('deleted', 'archived' )";
       $row = $this->db->getAll($sql);
       return $row;
   }
   
   public function actionpurchaserawmaterial($company_id, $element_id, $num){
        $cashinfo = $this->getcash_equivalent($company_id);
        //echo '<h3>现金及现金等价物：'; 
        $cash = 0;
        $deposit = 0;
        $sql = 'select * from raw_material_list where element_id = ' . $element_id;
        $elementinfo = $this->db->getRow($sql);
        $sql = 'select element_name from company_element_list where element_id = ' . $element_id;
        $elementinfo['element_name'] = $this->db->getOne($sql);        
        $raw_material_value = $elementinfo['raw_material_price'];
        
        //以下代码用来判断资金是否足够购买这么多材料        
        foreach($cashinfo as $k=>$v){ 
            if($k == '库存现金'){
                $cash = $v;   
            }
            
            if($k == '银行存款'){
                $deposit = $v;
            }
        }
        $ttlcashequivalent = $cash + $deposit;        
        $action_amount =  $num * $raw_material_value;  
        //echo $action_amount . '|||' . $ttlcashequivalent;
        
         if ($ttlcashequivalent< $action_amount){
            return false;         
         }
         

         //以下代码用来生成actionlog          
         $action_id =  6;
         
         //print_r($elementinfo);
         
         $element_name = $elementinfo['element_name'];
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '购买原材料：' . $element_name . '，数量：' . $num . '个。';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'element_id'=>$element_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_price'=>$raw_material_value, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();         
         
         
        
        //以下代码输入新购买的元素
         $raw_material_trans =  $elementinfo['raw_material_trans'];
         $rawmaterialtagidlist= array();
         $rawmaterial = array('element_id'=>$element_id, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'element_value'=>$raw_material_value, 'raw_material_trans'=>$raw_material_trans);
    
         for($i=1; $i<=$num; $i++){
              $tagid = $this->insertelement('raw_material', $rawmaterial);
              $rawmaterialtagidlist[] = $tagid; 
         }
         
         //以下代码从银行存款及现金内削减相应的金额
         $this->deductcash($company_id, $action_amount);
 
         
         //以下代码用来输入记账凭证
         $bookinginfo =array();
         if($deposit >=$action_amount ){
            //记账凭证:使用银行存款购买
            $bookinginfo[1402] = $action_amount;
            $bookinginfo[1002] =  - $action_amount;
            $this-> insertdailybooking ($actionlogid, $bookinginfo);

         }else{
            $bookinginfo[1402] = $action_amount;
            $bookinginfo[1002] =  - $deposit;
            $bookinginfo[1001] =  - ($action_amount - $deposit);
            $this-> insertdailybooking ($actionlogid, $bookinginfo); 
         }
         $row = array($actionlogid=>$rawmaterialtagidlist);
         return $row; 
   
   }
   
   
   public function actionpurchaseequipment($building_tagid, $position, $element_id){
       $sql =  'select company_id from building where building_tagid = ' . $building_tagid;
       $company_id = $this->db->getOne($sql);
       
        $cashinfo = $this->getcash_equivalent($company_id);
        //echo '<h3>现金及现金等价物：'; 
        $cash = 0;
        $deposit = 0;
        $sql = 'select * from equipment_list where element_id = ' . $element_id;
        $elementinfo = $this->db->getRow($sql);
        $sql = 'select element_name from company_element_list where element_id = ' . $element_id;
        $elementinfo['element_name'] = $this->db->getOne($sql);        
        $equipment_value = $original_value = $elementinfo['equipment_price'];
        
         //以下代码用来判断资金是否足够购买这么多材料        
        foreach($cashinfo as $k=>$v){ 
            if($k == '库存现金'){
                $cash = $v;   
            }
            
            if($k == '银行存款'){
                $deposit = $v;
            }
        }
        $ttlcashequivalent = $cash + $deposit;        
        $action_amount =  $equipment_value;  
        //echo $action_amount . '|||' . $ttlcashequivalent;
        
         if ($ttlcashequivalent< $action_amount){
            return false;         
         }
         
         //以下代码用来生成actionlog          
         $action_id =  5;
         
         //print_r($elementinfo);
         
         $element_name = $elementinfo['element_name'];
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '购买生产线一条：' . $element_name;
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'element_id'=>$element_id, 'action_volume'=>1, 'action_amount'=>$action_amount, 'action_price'=>$equipment_value, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id(); 
         
         
          //以下代码输入新购买的元素
         $installation_period =  $elementinfo['installation_period'];
         $equipmenttagidlist= array();
         $equipment = array('element_id'=>$element_id, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'original_value'=>$original_value,'element_value'=>$equipment_value, 'installation_period'=>$installation_period, 'building_tagid' =>$building_tagid, 'position_in_building'=>$position);

         $tagid = $this->insertelement('equipment', $equipment);
         $equipmenttagidlist[] = $tagid;
         
         
                 
         //以下代码从银行存款及现金内削减相应的金额
         $this->deductcash($company_id, $action_amount);
 
         
         //以下代码用来输入记账凭证
         $bookinginfo =array();
         if($deposit >=$action_amount ){
            //记账凭证:使用银行存款购买
            $bookinginfo[1604] = $action_amount;
            $bookinginfo[1002] =  - $action_amount;
            $this-> insertdailybooking ($actionlogid, $bookinginfo);

         }else{
            $bookinginfo[1604] = $action_amount;
            $bookinginfo[1002] =  - $deposit;
            $bookinginfo[1001] =  - ($action_amount - $deposit);
            $this-> insertdailybooking ($actionlogid, $bookinginfo); 
         }
         $row = array($actionlogid=>$equipmenttagidlist);
         return $row;
        
   } 
   
   public function actionupdaterawmaterialontheway($company_id){
       $timesofaction = $this->gettimesofaction($company_id, 9);
       if($timesofaction > 0){
            return false;
       }
       
        $rawmaterial = $this->getallelements($company_id, 'raw_material');
        $num = 0;
        $action_amount = 0;
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
        
        
        foreach($rawmaterial as $k=>$v){
            $tagid = $v['raw_material_tagid'];
            //以下代码判断是否是本季度新购入的原材料，如果是的话则无需更新
            $purchaseaction_log_id = $v['action_log_id'];
            $sql = 'select action_log_y from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_y = $this->db->getOne($sql);
            $sql = 'select action_log_q from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_q = $this->db->getOne($sql);
            
            if(($purchase_y == $company_y)&&($purchase_q == $company_q) ){
                continue;
            }
            //以上代码判断是否是本季度新购入的原材料，如果是的话则无需更新      
            $trans = $v['raw_material_trans'];
            if($trans>1){
                $trans = $trans - 1;
                $arr = array('raw_material_trans'=>$trans);
                $this->db->autoExecute($arr, 'raw_material', 'update', ' where raw_material_tagid = ' . $tagid);
            }else if($trans==1){
                $trans = 0;
                $num = $num + 1;
                $action_amount = $action_amount + $v['element_value'];
                $arr = array('raw_material_trans'=>$trans);
                $this->db->autoExecute($arr, 'raw_material', 'update', ' where raw_material_tagid = ' . $tagid);                
            }
        }
        
           
       
       
       //以下代码用来生成actionlog          
         $action_id =  9;
         
         //print_r($elementinfo);
         
         $element_name = '原材料';
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '更新在途原材料';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         
          //以下代码用来输入记账凭证
          if($action_amount>0){         
                $bookinginfo =array();
                $bookinginfo[1403] = $action_amount;
                $bookinginfo[1402] =  - $action_amount;
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
         return $num;
  
  }
  
  
  public function gettimesofaction($company_id, $action_id){
      $sql = 'select * from company where company_id = ' . $company_id;
      $companyinfo = $this->db->getRow($sql);
      $company_y = $companyinfo['company_y'];
      $company_q = $companyinfo['company_q'];
      
      $sql = "select count(*) from action_log where action_id = " . $action_id . " and company_id = " . $company_id . " and action_log_y =  " . $company_y . " and action_log_q = " . $company_q . " and deleteflg not in ('deleted', 'archived' )";
      $num = $this->db->getOne($sql);
      return $num;
  }
  
  public function actionupdateunfinishedequipment($company_id){
       $timesofaction = $this->gettimesofaction($company_id, 4);
       if($timesofaction > 0){
            return false;
       }
       
        $equipment = $this->getallelements($company_id, 'equipment');
        $num = 0;
        $action_amount = 0;
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
        
        foreach($equipment as $k=>$v){
            $tagid = $v['equipment_tagid'];
            //以下代码判断是否是本季度新购入的生产线，如果是的话则无需更新
            $purchaseaction_log_id = $v['action_log_id'];
            $sql = 'select action_log_y from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_y = $this->db->getOne($sql);
            $sql = 'select action_log_q from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_q = $this->db->getOne($sql);
            
            if(($purchase_y == $company_y)&&($purchase_q == $company_q) ){
                continue;
            }
            //以上代码判断是否是本季度新购入的生产线，如果是的话则无需更新
            $instal = $v['installation_period'];
            if($instal>1){
                $instal = $instal - 1;
                $arr = array('installation_period'=>$instal);
                $this->db->autoExecute($arr, 'equipment', 'update', ' where equipment_tagid = ' . $tagid);
            }else if($instal==1){
                $instal = 0;
                $num = $num + 1;
                $action_amount = $action_amount + $v['element_value'];
                $arr = array('installation_period'=>$instal);
                $this->db->autoExecute($arr, 'equipment', 'update', ' where equipment_tagid = ' . $tagid);                
            }
        }

       
       //以下代码用来生成actionlog          
         $action_id =  4;
         
         //print_r($elementinfo);
         
         $element_name = '生产线';
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '更新在建生产线';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
                
         
          //以下代码用来输入记账凭证
          if($action_amount>0){          
                $bookinginfo =array();
                $bookinginfo[1601] = $action_amount;
                $bookinginfo[1604] =  - $action_amount;
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
         return $num; 
      
  }
  public function actionupdateunfinishedgood($company_id){
       $timesofaction = $this->gettimesofaction($company_id, 8);
       if($timesofaction > 0){
            return false;
       }
       
        $product = $this->getallelements($company_id, 'product');
        $num = 0;
        $action_amount = 0;
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
        
        
        foreach($product as $k=>$v){
            $tagid = $v['product_tagid'];
            //以下代码判断是否是本季度新上线的产品，如果是的话则无需更新
            $purchaseaction_log_id = $v['action_log_id'];
            $sql = 'select action_log_y from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_y = $this->db->getOne($sql);
            $sql = 'select action_log_q from action_log where action_log_id = ' . $purchaseaction_log_id;
            $purchase_q = $this->db->getOne($sql);
            
            if(($purchase_y == $company_y)&&($purchase_q == $company_q) ){
                continue;
            }
            //以上代码判断是否是本季度新上线的产品，如果是的话则无需更新           
            
            $produce = $v['produce_period'];
            if($produce>1){
                $produce = $produce - 1;
                $arr = array('produce_period'=>$produce);
                $this->db->autoExecute($arr, 'product', 'update', ' where product_tagid = ' . $tagid);
            }else if($produce==1){
                $produce =0;
                $num = $num + 1;
                $action_amount = $action_amount + $v['product_value'];
                $arr = array('produce_period'=>$produce);
                $this->db->autoExecute($arr, 'product', 'update', ' where product_tagid = ' . $tagid);           
            }
        }
        
        //以下代码用来生成actionlog          
         $action_id =  8;
         
         //print_r($elementinfo);
         
         $element_name = '在制品';
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '更新在制品';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
            
          //以下代码用来输入记账凭证
          if($action_amount>0){
                $bookinginfo =array();
                $bookinginfo[1405] = $action_amount;
                $bookinginfo[5001] =  - $action_amount;
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
         return $num; 
  
  }
  
  public function actionselltothemarket($company_id, $element_id, $num){
      $sql = 'select element_name from company_element_list where element_id = ' . $element_id;
      $element_name = $this->db->getOne($sql);     
      $finishedgood = $this->getfinishedgood($company_id);
      
      if(array_key_exists($element_name, $finishedgood)){
          //$marketprice = $this->getmarketprice($element_id, $y, $q);
          //以下代码判断是否有足够库存
          if($finishedgood[$element_name]<$num){
                return false;
          }
         
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
          $marketprice = $this->getmarketprice($element_id, $company_y, $company_q);
          $action_amount = $num * $marketprice;
          
          //以下代码用来生成actionlog          
         $action_id =  20;
         
         //print_r($elementinfo);
         
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '把' . $element_name . '卖向市场，数量：' . $num . '；价格：' .  $marketprice . '。' ;
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>$num, 'action_amount'=>$action_amount, 'action_price'=>$marketprice, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         //以下代码用来删除现有的库存
         $cost = 0; 
         $sql="select * from product where company_id = " . $company_id . " and element_id = " . $element_id . " and produce_period = 0 and deleteflg not in ('deleted', 'archived' )";
         $product = $this->db->getAll($sql);
         for($i = 1; $i <=$num; $i++){
             reset($product);
             $good = current($product);
             $tagid = $good['product_tagid'];
             $cost = $cost + $good['product_value'];
             $arr = array('deleteflg'=>'deleted');
             $this ->db->autoExecute($arr, 'product', 'update' , ' where product_tagid = ' . $tagid);
             array_shift($product);
         }
         
         //以下代码用来增加一笔银行存款收入
        $arr = array('element_id'=>6002, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'original_value'=>$action_amount, 'current_value'=>$action_amount, 'format'=>'Bank Deposit'); 
        $this->db->autoExecute($arr, 'cash_equivalent', 'insert');
        
        
        //以下代码用来输入记账凭证
          if($action_amount>0){
                $bookinginfo =array();
                $bookinginfo[1002] = $action_amount;
                $bookinginfo[6001] =  - $action_amount; 
                $bookinginfo[6401] =  $cost;     
                $bookinginfo[1405] =  - $cost;
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
          return $action_amount;
      }else{
            return false;
      }
  }
  
  public function getelementid($element_name){
      $sql = 'select element_id from company_element_list where element_name = "' . $element_name . '"';
      return $this->db->getOne($sql);  
  }
  
  public function getelementname($element_id){
      $sql = 'select element_name from company_element_list where element_id = ' . $element_id;
      return $this->db->getOne($sql);  
  }
  
  public function actioncarryover($company_id){
              
         //以下代码用来生成actionlog          
         $action_id =  17;
         
         //print_r($elementinfo);
         
         $element_name = '损益类账户';
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '期末结转损益类账户';
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>0, 'action_amount'=>0, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         $accounting = new accountingmodel();
         $accounting->carryover($company_id, $actionlogid);
         return true;
  }
  
     public function actionaccruedincometax($company_id){
       //判断是否所有的损益类账户都已经结转
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         
         $sql = 'select * from account_list where account_category = "损益" and account_level = 1' ;
         $pnlaccount = $this->db->getAll($sql);
         
         
         foreach($pnlaccount as $k=>$v){
             $accountid = $v['account_id'];
             $sql = "select * from account_daily_booking where account_id = " . $accountid . " and deleteflg not in ('deleted', 'archived' )";
             $dailybooking = $this->db->getAll($sql);
             $balance = 0;
             foreach($dailybooking as $key=>$value){
                 $actionlogid = $value['action_log_id'];
                 $sql = 'select company_id from action_log where action_log_id = ' . $actionlogid;
                 $companyid = $this->db->getOne($sql);
                 $sql = 'select action_log_y from action_log where action_log_id = ' . $actionlogid; 
                 $actionlogy = $this->db->getOne($sql);
                 $sql = 'select action_log_q from action_log where action_log_id = ' . $actionlogid; 
                 $actionlogq = $this->db->getOne($sql);                 
                 
                 if(($companyid == $company_id)&&($actionlogy==$company_y)&&($actionlogq==$company_q)) {
                     $amount = $value['amount'];
                     $debitcredit = $value['debit_credit'];
                     if($debitcredit == 'debit'){
                            $balance = $balance + $amount;                         
                     }else{
                            $balance = $balance - $amount;   
                     }
                 }                 
             }
             
             if($balance!=0){
                return false;             
             }
         }
         
         //判断本年度是否已经计提过税收         
         $sql = "select count(*) from action_log where action_id = 18 and company_id = " . $company_id . " and action_log_y = " . $company_y  . " and action_log_q = " . $company_q . " and  deleteflg not in ('deleted', 'archived' )";
         $isdone = $this->db->getOne($sql);
         if($isdone>0){
                return false;
         }
         
         //找到本年度结转损益的actionlogid,  注意，在本规则下，每个季度在计提所得税之前，只能结转一次损益账户。
         $sql = "select action_log_id from action_log where action_id = 17 and company_id = " . $company_id . " and action_log_y = " . $company_y  . " and action_log_q = " . $company_q . " and  deleteflg not in ('deleted', 'archived' )";
         $carryoveractionlogid = $this->db->getOne($sql);
         
         
         //计提税收
         $sql = "select * from account_daily_booking where account_id = 4103 and action_log_id = " . $carryoveractionlogid . " and deleteflg not in ('deleted', 'archived' )";                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
         $earningsbeforetax =  $this->db->getAll($sql);
         $earning=0;
         foreach($earningsbeforetax as $k=>$v){
             $amount = $v['amount'];
             $debitcredit = $v['debit_credit'];
             if($debitcredit == 'debit'){
                  $earning = $earning + $amount;                 
             }else{
                  $earning = $earning - $amount;                 
             }
         }
         
         if( $earning >0 ){//利润为负
                $incometax = 0; 
         }else{
                $incometax = -$earning * 0.25;// 所得税率为25%
         }
         
         //形成本次动作actionlogid     
         $action_id =  18;
         
         //print_r($elementinfo);
         
          $action_amount = $incometax;
         
         $element_name = '应缴税费';
         $datetime = date('Y-m-d H:i:s', time());
         $logcontent = '计提应付税->所得税：' . $incometax;
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_volume'=>0, 'action_amount'=> $action_amount, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         //以下还应该写一段代码把应交税作为一个element来处理，尚未建立应交税的elementlist
         
         //以下代码写入dailybooking
         
         if( $action_amount>0){
                $bookinginfo =array();
                $bookinginfo[6801] = $action_amount;
                $bookinginfo[2221] =  - $action_amount; 
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
          return  $action_amount;
   }
   
   public function actioncapitalinjection($company_id, $capital){
         //以下代码用来生成actionlog          
         $action_id =  21;
         $action_amount = $capital;
         
         //print_r($elementinfo);
         
         $datetime = date('Y-m-d H:i:s', time());
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $logcontent = '资本注入，金额：' . $capital;
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'action_amount'=>$action_amount, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         //以下代码生成一条新的deposit
         
         $arr = array('element_id'=>6002, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'original_value'=>$action_amount, 'current_value'=>$action_amount, 'format'=>'Bank Deposit');
         $this->insertelement('cash_equivalent', $arr);
         
         //以下代码生成dailybooking
         
         if( $action_amount>0){
                $bookinginfo =array();
                $bookinginfo[1002] = $action_amount;
                $bookinginfo[4001] =  - $action_amount; 
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
          return  true;
   }
   
   public function actionapplyforloan($company_id, $element_id, $amount){
       //判断该公司能否申请这么多贷款，该段代码尚未编写
       
       $sql = 'select * from loan_list where element_id = '. $element_id;
       $loaninfo = $this->db->getRow($sql);
       $sql = 'select element_name from company_element_list where element_id = '. $element_id;  
       $element_name = $this->db->getOne($sql);
       
       $duration = $loaninfo['duration'];
       $action_price = $interestrate = $loaninfo['interest_rate'];
       
       
       //以下生成actionlog
       
        //以下代码用来生成actionlog          
         $action_id =  11;
         $action_amount = $amount;
         
         //print_r($elementinfo);
         
         $datetime = date('Y-m-d H:i:s', time());
         $sql = 'select * from company where company_id = ' . $company_id;
         $companyinfo = $this->db->getRow($sql);
         $company_y = $companyinfo['company_y'];
         $company_q = $companyinfo['company_q'];
         $logcontent = '申请贷款：' . $element_name . '&nbsp&nbsp金额：' . $amount;
         $actionlog = array('action_id'=>$action_id, 'company_id'=>$company_id, 'element_id'=>$element_id, 'action_amount'=>$action_amount, 'action_price'=>$action_price, 'action_log_content'=>$logcontent, 'action_log_y'=>$company_y, 'action_log_q'=>$company_q, 'action_time'=>$datetime); 
         $this->db->autoExecute($actionlog, 'action_log', $mode='insert');
         $actionlogid = $this->db->insert_id();
         
         //以下代码生成新的loan
         $arr = array('element_id'=>$element_id, 'action_log_id'=>$actionlogid, 'company_id'=>$company_id, 'original_value'=>$action_amount, 'current_value'=>$action_amount, 'duration'=>$duration, 'interest_rate'=>$interestrate);
         $this->insertelement('loan', $arr);
         
         //以下代码生成新的dailybooking         
         
         if( $action_amount>0){
                $bookinginfo =array();
                $bookinginfo[1002] = $action_amount;
                if($duration >= 4){
                      $bookinginfo[2501] =  - $action_amount;
                }else{
                        $bookinginfo[2001] =  - $action_amount;
                } 
                $this-> insertdailybooking ($actionlogid, $bookinginfo);
          }
          
          return  true;
         
       
   
   
   }
   
   public function getmarketprice($element_id, $y, $q){
       return  5600000;   
   }
   
   public function getorder($company_id){
    $sql = "select * from product_order where company_id = " . $company_id . " and deleteflg not in ('deleted', 'archived' ) order by element_id asc";
    return $this->db->getAll($sql);   
   }
   
  }
  
?>
